package com.tianji.promotion.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
public class MyLock {

    private final String lockName;
    private final StringRedisTemplate redisTemplate;

    public MyLock(String lockName, StringRedisTemplate redisTemplate){
        this.lockName = lockName;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 尝试获取一把锁
     * */
    public boolean tryLock(long expireTime, TimeUnit unit){
        // 当前线程的名称
        String threadName = Thread.currentThread().getName();
        Boolean locked = redisTemplate.opsForValue().setIfAbsent(lockName, threadName, expireTime, unit);
        if(locked != null && locked){
            //获取锁成功
            log.info("获取锁：{}成功 ", lockName);
            return true;
        }else{
            // 获取锁失败
            log.info("获取锁：{}失败 ", lockName);
            return false;
        }
    }

    // lua脚本：原子性操作
    public void release(){
        // 首先是获取redis中lock的value
        String value = redisTemplate.opsForValue().get(lockName);

        // 获取当前的线程名
        String threadName = Thread.currentThread().getName();

        // 比较
        if(Objects.equals(value, threadName)){

            redisTemplate.delete(lockName);
        }
    }

    public static void main(String[] args) {
        MyLock myLock = new MyLock(null, null);
        myLock.f1();
    }

    public synchronized  void f1(){
        f2();
    }
    public synchronized  void f2(){

    }
    public static   void f3(){
        synchronized (MyLock.class){

        }
    }
}
